package dao;

import bean.ChatGroup;
import bean.User;
import utils.JDBCUtils;

import java.security.acl.Group;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

public class UserDao {
    static HashSet<String> uid = new HashSet<>();


    /**
     * 生成1个8位数字，
     *
     * @return
     */
    public String getRandomId() {
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            //首字母不能为0
            result.append(random.nextInt(9) + 1);
        }
        while (!uid.contains(result.toString())) {
            for (int i = 0; i < 8; i++) {
                //首字母不能为0
                result.append(random.nextInt(9) + 1);
            }
        }
        uid.add(result.toString());

        return result.toString();
    }

    public User isLogin(String userName, String passWord) {
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();

            String sql = "select * from chat.user where userName = '" + userName + "' and passWord = '" + passWord + "'  ";
             ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            int count = -1;
            User user = null;
            if (rs.next()) {
                 user = new User(
                        rs.getString("id"),
                        rs.getString("userName"),
                        rs.getString("img"),
                        rs.getString("email"),
                        rs.getString("passWord"),
                        rs.getString("signature"),
                        rs.getString("mobile")
                );
            }
            if (user != null) {
                return user;
            } else {
                return null;
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建一个新用户并插入数据库
     *
     * @param user
     * @return
     * @throws SQLException
     */
    public boolean insert(User user) throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        String id = null;
        int num = 0;
        //如果用户名不为空，则生成一个8位随机id
        if (user.getUserName() != null) {
            id = getRandomId();
        }
        try {
            conn = JDBCUtils.getConnection();
            String sql = "insert into chat.user(id,userName,passWord,img,signature,email,mobile) values (?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.setString(2, user.getUserName());
            pstmt.setString(3, user.getPassWord());
            num = pstmt.executeUpdate();

            if (num > 0) {
                return true;
            } else {
                return false;
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(pstmt, conn);
        }
        return false;

    }

    /**
     * 修改user信息
     *
     * @param user
     * @param information 信息类型
     * @return
     * @throws SQLException
     */
    public boolean reset(User user, String information) throws SQLException {

        Connection conn = null;
        PreparedStatement pstmt = null;
        int num = 0;

        try {
            conn = JDBCUtils.getConnection();

            String sql = "update chat.user set" + information + "=? where  id=?";
            pstmt = conn.prepareStatement(sql);
            if (information != null) {
                switch (information) {
                    case "passWord":
                        pstmt.setString(1, user.getPassWord());
                        break;
                    case "userName":
                        pstmt.setString(1, user.getUserName());
                        break;
                    case "img":
                        pstmt.setString(1, user.getImg());
                        break;
                    case "email":
                        pstmt.setString(1, user.getEmail());
                        break;
                    case "mobile":
                        pstmt.setString(1, user.getMobile());
                        break;
                    default:
                        return false;
                }

            }
            pstmt.setString(2, user.getId());
            num = pstmt.executeUpdate();

            return num > 0;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(pstmt, conn);
        }
        return false;


    }

    /**
     * 添加好友
     *
     * @param user
     * @param friend
     * @return
     */
    public boolean addFriend(User user, User friend) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        String id = null;
        int num = 0;
        System.out.println(user.getId());
        System.out.println(friend.getId());
        try {
            conn = JDBCUtils.getConnection();
            String sql = "insert into chat.userfriend(userId, friendId) values (?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getId());
            pstmt.setString(2, friend.getId());

            String sql2 = "insert into chat.userfriend(friendId, userId) values (?,?)";
            pstmt = conn.prepareStatement(sql2);
            pstmt.setString(1, friend.getId());
            pstmt.setString(2, user.getId());

            num = pstmt.executeUpdate();

            return num > 0;

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                JDBCUtils.release(pstmt, conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return false;

    }

    /**
     * 根据id找User
     * @param id
     * @return
     */
    public User findUser(String id) {

        try {
            Connection conn = JDBCUtils.getConnection();
            String sql = "select * from chat.user where id=" + id;
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                return new User(
                 rs.getString("id"),
                 rs.getString("userName"),
                 rs.getString("img"),
                 rs.getString("email"),
                 rs.getString("passWord"),
                 rs.getString("signature"),
                 rs.getString("mobile")
                );
            }


        } catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /**
     * 根据用户id找friend
     * @param id
     * @return
     */
    public List<String> findAllFriend(String id){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<String> list = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select friendId from chat.userfriend where userId = "+id;
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                list.add(rs.getString("friendId"));
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    public List<ChatGroup> findAllGroup(String id){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<ChatGroup> list = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select chatGroupID from chat.chatgroupuser where userId = "+id;
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            ChatGroupDao chatGroupDao = new ChatGroupDao();
            while (rs.next()){
                list.add(chatGroupDao.findGroup(rs.getString("chatGroupID")));
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return list;
    }
}

